import {createRouter, createWebHistory, Router} from 'vue-router'

const router:Router = createRouter({
    history: createWebHistory(import.meta.env.BASE_URL),
    routes: [
        {
            path: '/',
            name: 'index',
            component:import ('@/views/Index.vue'),
            meta:{
                title:'主页'
            }
        },
        {
            path: '/login',
            name: 'login',
            component:import ('@/views/Login.vue'),
            meta:{
                title:'登录'
            }
        },
        {
            path: '/register',
            name: 'register',
            component:import ('@/views/Register.vue'),
            meta:{
                title:'注册'
            }
        },
        {
            path: '/backend',
            name: 'backend',
            component:import ('@/views/Backend.vue'),
            meta:{
                auth: true,
                title:'后台'
            }
        },
    ]
})

router.beforeEach(async (to, from, next) => {
    // 判断该路由是否需要登录权限
    if (to.matched.some(record => record.meta.auth) && to.meta.auth) {
        let token = localStorage.getItem('cloudToken');
        if (token) { // 获取当前的 token 是否存在
            next();
        } else {
            // 不存在 token，需要重新认证
            next({
                path: '/login'
            })
        }
    }
    next();
});

export default router
